<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Services\LaborAttendanceService;
use Illuminate\Http\Request;

class LaborAttendanceController extends Controller
{
    protected $LaborAttendanceService;
    public function __construct(LaborAttendanceService $LaborAttendanceService)
    {
        $this->LaborAttendanceService = $LaborAttendanceService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $name = $request->name;
        $team_id = $request->team_id;
        $labor_id = $request->labor_id;
        $pageSize = $request->pageSize ?: 10;
        $page = $request->page ?: 1;
        $page = $page * $pageSize - $pageSize;

        $sql = $this->LaborAttendanceService->get();
        $sql->where('company_id',$request->company_id);
        $sql->where('project_id',$request->project_id);
        if($team_id){
            $sql->where('team_id',$request->team_id);
        }
        if($labor_id){
            $sql->where('labor_id',$request->labor_id);
        }
        if($request->start_date){
            $sql->whereDate('attendance_date',' >= ',Date('Y-m-d',$request->start_date / 1000));
        }
        if($request->end_date){
            $sql->whereDate('attendance_date',' <= ',Date('Y-m-d',$request->end_date / 1000));
        }
        // name
        $sql->whereHas('labor', function ($query) use ($name) {
            $query->where('name', 'like', '%'.$name.'%');
        });
        $total = $sql->count();
        $data = $sql->skip($page)->take($pageSize)->orderBy('created_at','desc')->get();
        foreach ($data as $k => $v) {
            $data[$k]->project_name = '';
            $data[$k]->project_number = '';

            $data[$k]->team_name = '';
            $data[$k]->name = '';
            $data[$k]->mobile = '';
            if($v->project){
                $data[$k]->project_name = $v->project->name;
                $data[$k]->project_number = $v->project->number;
            }

            if($v->team){
                $data[$k]->team_name = $v->team->name;
            }

            if($v->labor){
                $data[$k]->name = $v->labor->name;
                $data[$k]->mobile = $v->labor->mobile;
            }
        }
        return response()->json(['code' => 200, 'message' => '操作成功','page'=>$page,'pageSize'=>$pageSize,'total'=>$total,'data'=>$data]);
    }


    public function laborStatistics(Request $request)
    {
        $team_id = $request->team_id;
        $labor_id = $request->labor_id;
        $data = $this->LaborAttendanceService->laborStatistics($request->company_id,$labor_id,$team_id,$request->project_id,$request->start_date,$request->end_date);
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }


}
